/**
 * @author yxw
 * date : 2014年1月31日 下午8:15:28 
 */
package com.tzinfo.tzb;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.DiaryList;
import com.tzinfo.tzb.util.TzbCommonData;
import com.yxw.util.OutLog;
import com.yxw.util.YXWDateUtil;
import com.yxw.view.YXWXListView;
import com.yxw.view.YXWXListView.IXListViewListener;
import com.yxw.view.adapter.ImageAdapter;
import com.yxw.view.util.ResFinder;

public class TzbDirayListActivity extends TzbBaseActivity implements
		IXListViewListener {
	// 标志

	// 参数
	private String username = null;

	// 适配器
	private ImageAdapter imageAdapter;

	// 数据
	public static DiaryList diaryList = null;

	// UI组件
	private YXWXListView listView;
	private RelativeLayout layout_no_listdata;

	// 其他
	private Handler mHandler;
	private int page = 1; // 页码
	private int pagesize = 10; // 每页条数

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(ResFinder.getR(this, "R.layout.tzb_ac_diraylist"));
		initParameter();
		initUI();
		initData();
		listView.setSelection(TzbCommonData.POSITION);
	}

	private void initParameter() {
		Intent thisIntent = this.getIntent();
		username = thisIntent.getStringExtra("username");
		if (username == null) {
			username = TztData.userInfo.getData().getUserName();
		}
		// classSubMenu = (ClassSubMenu) thisIntent
		// .getSerializableExtra("classSubMenu");
		mHandler = new Handler();
	}


	private void initUI() {
		// 加载滚动进入条
		mProgressBar = (ProgressBar) this.findViewById(ResFinder.getR(this,
				"R.id.progressbar_loding"));
		listView = (YXWXListView) ResFinder
				.findViewById(this, "R.id.xListView");
		layout_no_listdata = (RelativeLayout) ResFinder.findViewById(this,
				"R.id.layout_no_listdata");
		listView.setPullLoadEnable(true);
		listView.setPullRefreshEnable(true);
		listView.setXListViewListener(this);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterview, View view,
					int i, long l) {
				if (diaryList != null) {
					Intent intent = new Intent(TzbDirayListActivity.this,
							TzbMyDirayDetailActivity.class);
					intent.putExtra("flag", 1);
					TzbCommonData.diaryItem = (int) l;
					TzbDirayListActivity.this.startActivityForResult(intent, 1);
				}
			}
		});
	}

	private void initData() {
		if (TzbCommonData.forumthreadList == null
				|| !TzbCommonData.forumthreadList.isSuccess()) {
			requestInfo();
		} else {
			initListView();
		}
	}

	private void initListView() {
		if (diaryList == null || diaryList.getData().size() == 0) {
			requestInfo();
			return;
		}
		listView.setVisibility(View.VISIBLE);
		layout_no_listdata.setVisibility(View.GONE);
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < diaryList.getData().size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			if (diaryList.getData().get(i).getPhoto().size() > 0) {
				String imageUil = diaryList.getData().get(i).getPhoto().get(0)
						.getPicfile();
				map.put("image", imageUil);
			} else {
				map.put("image", ResFinder.getR(this, "R.drawable.ic_empty"));
			}

			map.put("title", diaryList.getData().get(i).getTitle());
			String time = YXWDateUtil.getTimeByDayInterval(diaryList.getData()
					.get(i).getPtime(), "yyyy-MM-dd");
			map.put("time", time);
			map.put("username", diaryList.getData().get(i).getUsername());
			map.put("supports", diaryList.getData().get(i).getSupports());
			data.add(map);
		}
		imageAdapter = new ImageAdapter(this, data, ResFinder.getR(this,
				"R.layout.tzb_item_riji"), new String[] { "image", "title",
				"time", "username", "supports" }, new int[] {
				ResFinder.getR(this, "R.id.list_item_image"),
				ResFinder.getR(this, "R.id.list_item_title"),
				ResFinder.getR(this, "R.id.list_item_time"),
				ResFinder.getR(this, "R.id.list_item_netname"),
				ResFinder.getR(this, "R.id.list_item_supports") });
		listView.setAdapter(imageAdapter);
		removeProgressBar();
	}

	// 重载，默认请求新数据
	private void requestInfo() {
		page = 1;
		requestInfo(TzbCommonData.NOPULL_LOAD);
	}

	private void requestInfo(int type) {
		final int type2 = type;
		if (type == TzbCommonData.NOPULL_LOAD) {
			showProgressBar();
		}
		String url = ResFinder.getResString(this, "R.string.tzb_url_DiaryList")
				+ "?username=" + username + "&Page=" + page + "&Pagesize="
				+ pagesize;
		OutLog.LogE("url", url);
		GalHttpRequest galHttpRequest = new GalHttpRequest(this, url);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<DiaryList>() {
				}.getType();
				DiaryList temp = gson.fromJson(arg0, type);
				if (temp != null && temp.isSuccess()) {
					if (type2 == TzbCommonData.PULL_LOAD_MORE) {
						int size = temp.getData().size();
						for (int i = 0; i < size; i++) {
							diaryList.getData().add(temp.getData().get(i));
						}
						if (size < 10) {
							listView.setPullLoadEnable(false);
							Toast.makeText(TzbDirayListActivity.this,
									"已经是最后一页！", Toast.LENGTH_LONG).show();
						}
					} else if (type2 == TzbCommonData.PULL_REFLASH
							|| type2 == TzbCommonData.NOPULL_LOAD) {
						diaryList = temp;
						if (temp.getData().size() < 10) {
							listView.setPullLoadEnable(false);
						} else {
							listView.setPullLoadEnable(true);
						}
					}
					initListView();
					onLoadFinish();
				} else {
					Toast.makeText(TzbDirayListActivity.this, "数据加载失败…",
							Toast.LENGTH_LONG).show();
				}
				removeProgressBar();
				dialog.dismiss();
			}
		});
	}

	private void onLoadFinish() {
		listView.stopRefresh();
		listView.stopLoadMore();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		listView.setRefreshTime(df.format(new Date()));
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				page = 1;
				requestInfo(TzbCommonData.PULL_REFLASH);
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				page++;
				requestInfo(TzbCommonData.PULL_LOAD_MORE);
			}
		}, 2000);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1) {
			if (resultCode == 1) {
				boolean isOk = data.getBooleanExtra(TzbCommonData.IS_OK, false);
				if (isOk) {
					requestInfo();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
